package se.krutstampen.backend.domain.model.product;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.validation.constraints.NotNull;

@Entity
public class Firmware {

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FIRMWARE_GEN")
	@SequenceGenerator(name = "FIRMWARE_GEN", sequenceName = "FIRMWARE_SEQ", allocationSize = 1)
	@NotNull
	private Long id;

	@ManyToOne
	private OperatingSystem operatingSystem;

	private String name;

	@Lob
	@Basic(fetch = FetchType.LAZY)
	protected byte[] data;

	public OperatingSystem getOperatingSystem() {
		return operatingSystem;
	}

	public void setOperatingSystem(OperatingSystem operatingSystem) {
		this.operatingSystem = operatingSystem;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}

	public List<Product> getProducts() {
		return products;
	}

	public void setProducts(List<Product> products) {
		this.products = products;
	}

	@ManyToMany(mappedBy = "firmwares")
	private List<Product> products;

	public static class Builder {

		private Firmware firmware = new Firmware();

		public Builder setName(String name) {
			firmware.setName(name);
			return this;
		}


		public Builder setFile(File file) {
		
			Path path = Paths.get(file.getAbsolutePath());
			byte[] data = null; 			
			try {
				data = Files.readAllBytes(path);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}		
			firmware.setData(data);
			return this;
		}


		public Builder setOperatingSystem(OperatingSystem operatingSystem) {
			firmware.setOperatingSystem(operatingSystem);
			return this;
		}

		public Firmware build() {
			return firmware;
		}
	}

	public void addProduct(Product product) {
	
		if(products == null){
			products = new ArrayList<Product>();
		}
		products.add(product);
	}

}
